package binary_search_tree;

public class BinarySearchTree {

    static class TreeNode {
        public int key;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int key) {
            this.key = key;
        }
    }

    public TreeNode root;

    /**
     * 插入一个元素
     * @param key
     */
    public boolean insert(int key) {
        if (root == null) {
            root = new TreeNode(key);
            return true;
        }
        TreeNode father = null;
        TreeNode cur = root;
        while (cur != null) {
            if (cur.key == key) {
                return false;
            }
            if (key > root.key) {
                father  =cur;
                cur = cur.right;
            }else {
                father = cur;
                cur = cur.left;
            }
        }
        if (key > father.key) {
            father.right = new TreeNode(key);
        }else {
            father.left = new TreeNode(key);
        }
        return true;
    }
    //查找key是否存在
    public boolean search(int key) {
        if (root == null) {
            return false;
        }
        TreeNode cur = root;
        while (cur != null) {
            if (cur.key == key) {
                return true;
            }
            if (key < cur.key) {
                cur = cur.left;
            }else {
                cur = cur.right;
            }
        }
        return false;
    }
    //删除key的值
    public boolean remove(int key) {
        //找到对应节点
        if (root == null) {
            return false;
        }
        TreeNode father = null;
        TreeNode cur = root;
        while (cur != null) {
            if (cur.key == key) {
                removeNode(father,cur);
            }
            if (key < cur.key) {
                father = cur;
                cur = cur.left;
            }else {
                father = cur;
                cur = cur.right;
            }
        }
        return false;
    }
    public void removeNode(TreeNode father,TreeNode cur) {
        //1.没有子树
        if (cur.left == null && cur.right == null) {
            if (cur == root) {
                root = null;
                return;
            }
            if (cur.key < father.key) {
                father.left = null;
            }else {
                father.right = null;
            }
        }
        //2.只有左子树
        if (cur.left != null && cur.right == null) {
            if (cur == root) {
                root = cur.left;
                return;
            }
            if (cur.key < father.key) {
                
            }else {

            }
        }
    }

}
